/**
 * 
 */
package org.mythflow.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * @author dmfrey
 *
 */
public class ViewProgram extends Activity {

	private static final String TAG = "ViewProgram";

	private final Handler handler = new Handler();
	
	private WebView webView;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate( Bundle savedInstanceState ) {
		super.onCreate(savedInstanceState);
		Log.i( TAG, "onCreate : enter" );

		webView = new WebView(this);
		setContentView( webView );
		webView.getSettings().setJavaScriptEnabled( true );
		webView.addJavascriptInterface( new AndroidBridge(), "android" );

		webView.getSettings().setPluginsEnabled( true );

		Bundle extras = getIntent().getExtras();
		final String videoUrl = extras.getString( "filename" ) + ".flv";
		Log.i( TAG, "onCreate : videoUrl=" + videoUrl );
		final String videoLen = extras.getString( "length" );
		Log.i( TAG, "onCreate : videoLen=" + videoLen );

		webView.setWebViewClient( new WebViewClient() {

			@Override
			public void onPageFinished( WebView view, String url ) {
				Log.i( TAG, "onPageFinished : enter" );
				
				String js = "javascript:init('http://" + Preferences.getAddress( getApplicationContext() ) + ":" + Preferences.getWebPort( getApplicationContext() ) + "/" + Preferences.getMythwebContext( getApplicationContext() ) + "', '" + videoUrl + "', '" + videoLen + "')";
				Log.i( TAG, "onPageFinished : js=" + js );
				
				webView.loadUrl( js );

				Log.i( TAG, "onPageFinished : exit" );
			}
			
		});

		webView.loadUrl( "file:///android_asset/index.html" );

		Log.i( TAG, "onCreate : exit" );
	}

	@Override
	protected void onStart() {
		Log.i( TAG, "onStart : enter" );
		super.onStart();
		
		Log.i( TAG, "onStart : exit" );
	}

	@Override
	protected void onStop() {
		Log.i( TAG, "onStop : enter" );
		super.onStop();

		webView.destroy();
		
		Log.i( TAG, "onStop : exit" );
	}

	@Override
	protected void onPause() {
		Log.i( TAG, "onPause : enter" );
		super.onPause();

		webView.loadUrl( "javascript:pause()" );

		Log.i( TAG, "onPause : exit" );
	}

	@Override
	protected void onResume() {
		Log.i( TAG, "onResume : enter" );
		super.onResume();
		
		webView.loadUrl( "javascript:resume()" );
		
		Log.i( TAG, "onResume : exit" );
	}

	private class AndroidBridge {
		
		public void status( final String arg ) { // must be final
			handler.post( new Runnable() {
				public void run() {
					Log.i( TAG, "status=" + arg );
				}
			});
		}
		
		public void info( final String arg ) { // must be final
			handler.post( new Runnable() {
				public void run() {
					Log.i( TAG, arg );
				}
			});
		}

	}

}
